<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  -->
    <el-card>
      <el-row>
        <el-col :span="7">
          <el-input placeholder="请输入内容"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getUserList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="centerDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userlist"
                border
                stripe>
        <el-table-column type="index"
                         label="序·"></el-table-column>
        <el-table-column label="姓名"
                         prop="username"></el-table-column>
        <el-table-column label="邮箱"
                         prop="email"></el-table-column>
        <el-table-column label="电话"
                         prop="mobile"></el-table-column>
        <el-table-column label="角色"
                         prop="role_name"></el-table-column>
        <el-table-column label="状态"
                         prop="mg_state">
          <template v-slot:default="scope">
            <el-switch v-model="scope.row.mg_state"
                       @change="userStateChange(scope.row.id,scope.row.mg_state)">
            </el-switch>
          </template>

        </el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button type="primary"
                       icon="el-icon-edit"
                       circle
                       size="mini"
                       @click="showEditDialog(scope.row.id)"></el-button>

            <el-button type="danger"
                       icon="el-icon-delete"
                       circle
                       size="mini"
                       @click="deleted(scope.row.id)"></el-button>

            <el-tooltip effect="dark"
                        :enterable="false"
                        content="角色分配"
                        placement="top">
              <el-button type="warning"
                         icon="el-icon-star-off"
                         circle
                         size="mini">

              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     background
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 5, 8]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog title="添加用户"
               :visible.sync="centerDialogVisible"
               width="50%"
               @close="addClosed"
               center>

      <el-form :model="ruleForm"
               :rules="rules"
               ref="ruleForm"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息 -->
    <el-dialog title="修改用户信息"
               :visible.sync="xgVisible"
               width="50%"
               center
               @close="xgClosed">

      <el-form :model="xgForm"
               :rules="rules"
               ref="xgForm"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="xgForm.username"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="xgForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="xgForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="xgVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="xgAddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <el-dialog title="删除用户"
               :visible.sync="deletes"
               width="50%"
               center>
      <span>是否确定删除当前用户</span>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="deletes = false">取 消</el-button>
        <el-button type="primary"
                   @click="deleteEnd">确 定</el-button>
      </span>
    </el-dialog> -->

  </div>
</template>
<style scoped>
</style>

<script>
export default {
  data () {
    return {
      // 获取用户列表参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 8
      },
      userlist: [],
      total: 0,
      centerDialogVisible: false,
      // 添加用户表单
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单
      xgForm: {},
      // 添加表单验证规则
      rules: {
        username: [{
          required: true, message: '请输入用户名', trigger: 'blur'
        },
        {
          min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'
        }],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) === false) {
                callback(new Error('请输入正确的手机号'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      xgVisible: false,
      deletes: false,
      deleteId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 每页显示多少条
    handleSizeChange (newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getUserList()
    },
    // 监听页码值改变时
    handleCurrentChange (currentPage) {
      this.queryInfo.pagenum = currentPage
      this.getUserList()
    },
    // 监听 switch 开关状态
    async userStateChange (infoId, infoState) {
      const { data: res } = await this.$http.put(`users/${infoId}/state/${infoState}`)
      if (res.meta.status !== 200) {
        infoId = !infoId
        return this.$message.error('更新状态失败')
      }
      this.$message.success('状态更新成功')
    },
    // 关闭添加用户框时清空内容
    addClosed () {
      this.$refs.ruleForm.resetFields()
    },
    // 添加新用户
    addUser () {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.ruleForm)

        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('用户提交成功')
        // 关闭添加用户框
        this.centerDialogVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },

    // 获取当前用户参数
    async showEditDialog (id) {
      this.xgVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      this.xgForm = res.data
    },
    // 监听关闭修改用户信息
    xgClosed () {
      this.$refs.xgForm.resetFields()
    },

    // 修改信息提交
    xgAddUser () {
      this.$refs.xgForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.xgForm.id, {
          email: this.xgForm.email,
          mobile: this.xgForm.mobile
        })

        if (res.meta.status !== 200) {
          this.$message.error('更新用户失败')
        }
        this.$message.success('用户更新成功')
        // 关闭添加用户框
        this.xgVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // delete 用户
    async deleted (id) {
      const confirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') {
        this.$message.info('您取消了')
      } else {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) { this.$message.error('删除失败') }
        this.$message.success('删除成功')
        // 重新获取用户列表
        this.getUserList()
      }
    }
  }
}
</script>
